    //
//  SearchUsersViewController.m
//  SpendFunk
//
//  Created by dongmh on 5/8/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SearchUsersViewController.h"
#import "SpendFunkAppDelegate.h"
#import "image.h"
#import "Global.h"
@implementation SearchUsersViewController


 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)init{
	searching = NO;
    return self;
}



// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	[self initView];
}

- (void)initView{
	/// backgrounnd for find friends screen
	NSString *path = [[NSString alloc] initWithFormat:@"%@",IMG_BKGR_VIEW];
	UIImage *img = [UIImage imageNamed:path];
	UIImageView *imgvFFBkgr = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
	[imgvFFBkgr setImage:img];
	[self.view addSubview:imgvFFBkgr];
	[imgvFFBkgr setUserInteractionEnabled:YES];
	[imgvFFBkgr release];
	////	
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_HEADER];
	img = [UIImage imageNamed:path];
	UIImageView *imgvBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
	[imgvBar setImage:img];
	[self.view addSubview:imgvBar];
	[imgvBar setUserInteractionEnabled:YES];
	[imgvBar release];
	//back	
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_BACK];
	img = [UIImage imageNamed:path];	
	m_pBtnBack = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, img.size.width, img.size.height)];
	[m_pBtnBack setBackgroundImage:img forState:UIControlStateNormal];
	[m_pBtnBack setBackgroundColor:[UIColor clearColor]];
	[m_pBtnBack setTitle:@"Back" forState:UIControlStateNormal];
	m_pBtnBack.titleLabel.textColor = [UIColor whiteColor];
	[m_pBtnBack addTarget:nil action:@selector(onBackClick) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:m_pBtnBack];
	
	///Search
	[path release];
	path = [[NSString alloc] initWithFormat:@"%@",IMG_BTN_NEXT];
	img = [UIImage imageNamed:path];	
	m_pBtnSearch = [[UIButton alloc] initWithFrame:CGRectMake(320-5-img.size.width, 5, img.size.width, img.size.height)];
	[m_pBtnSearch setBackgroundImage:img forState:UIControlStateNormal];	
	[m_pBtnSearch setBackgroundColor:[UIColor clearColor]];
	[m_pBtnSearch setTitle:@"Search" forState:UIControlStateNormal];
	[m_pBtnSearch addTarget:nil action:@selector(onSeachClick) forControlEvents:UIControlEventTouchUpInside];
	[imgvBar addSubview:m_pBtnSearch];
	
	////
	UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20 + 45, 280, 20)];
	[label setBackgroundColor:[UIColor clearColor]];
	label.textAlignment = UITextAlignmentCenter;
	label.text = @"Input username for search:";
	[imgvFFBkgr addSubview:label];
	// Text
	m_pTxtUser = [[UITextField alloc] initWithFrame:CGRectMake(20, 50 + 45, 280, 20)];
	[m_pTxtUser setBackgroundColor:[UIColor blueColor]];
	[m_pTxtUser setAutocorrectionType:UITextAutocorrectionTypeNo];
	[imgvFFBkgr addSubview:m_pTxtUser];
	// test
	m_pTxtUser.text = @"son";
	// Please wait ... 
	_blockerView = [[[UIView alloc] initWithFrame: CGRectMake(0, 0, 200, 60)] autorelease];
	_blockerView.backgroundColor = [UIColor colorWithWhite: 0.0 alpha: 0.8];
	_blockerView.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
	_blockerView.alpha = 0.0;
	_blockerView.clipsToBounds = YES;
	if ([_blockerView.layer respondsToSelector: @selector(setCornerRadius:)]) [(id) _blockerView.layer setCornerRadius: 10];
	
	UILabel	*label1 = [[[UILabel alloc] initWithFrame: CGRectMake(0, 5, _blockerView.bounds.size.width, 15)] autorelease];
	label1.text = NSLocalizedString(@"Please Wait…", nil);
	label1.backgroundColor = [UIColor clearColor];
	label1.textColor = [UIColor whiteColor];
	label1.textAlignment = UITextAlignmentCenter;
	label1.font = [UIFont boldSystemFontOfSize: 15];
	[_blockerView addSubview: label1];
	
	UIActivityIndicatorView				*spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite] autorelease];
	
	spinner.center = CGPointMake(_blockerView.bounds.size.width / 2, _blockerView.bounds.size.height / 2 + 10);
	[_blockerView addSubview: spinner];
	[self.view addSubview: _blockerView];
	[spinner startAnimating];
}
- (void)onBackClick{
	[g_AppDelegate openFindFriends];
	[m_pTxtUser resignFirstResponder];
}
- (void)onSeachClick{
	_blockerView.alpha = 1.0;
	[self searchUser:m_pTxtUser.text userid:g_strLoginUserId];
	[m_pTxtUser resignFirstResponder];
	m_pTxtUser.text = nil;
	
}
- (void)searchUser:(NSString*)username userid:(NSString*)userid{
	
	searching = YES;
	NSString *emtyStr = [[NSString alloc] initWithFormat:@""];
	if ([username isEqualToString:emtyStr] || !username) 
	{
		_blockerView.alpha =0.0;
		UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please insert username for search" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
	else 
	{
		NSString *post = [[NSString alloc] initWithFormat:@"userid=%@&key=%@",userid,username];
		NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];  
		NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
		
		NSURL *url = [NSURL URLWithString:@"http://demo.thejupitech.com/snt/spendfunk/api/users/searchuser"];
		NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
		[theRequest setHTTPMethod:@"POST"];  
		[theRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];  
		[theRequest setHTTPBody:postData];	
		
		NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
		if( theConnection )
		{
			m_pWebData = [[NSMutableData data] retain];
			
			if(!m_pArrFriends){
				m_pArrFriends = [[NSMutableArray alloc] init];
			}else {
				[m_pArrFriends removeAllObjects];
			}
		}
		else
		{
			
		}
		
		//[self performSelector:@selector(resetAllInfo) withObject:nil afterDelay:0.5];
	}
	
}
#pragma mark -
#pragma mark connect delegate
#pragma mark delegate connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[m_pWebData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[m_pWebData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Cannot connect to internet" message:@"Please connect to internet!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	
	[alert release];
	[connection release];
	[m_pWebData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSData *loginStatus = [[NSData alloc] initWithBytes: [m_pWebData mutableBytes] length:[m_pWebData length]];
	
	NSString *a = [[NSString alloc] initWithData:loginStatus encoding:NSUTF8StringEncoding];
	NSLog(@"%@",a);
	
	NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:loginStatus];
	[xmlParser setDelegate:self];
	
	BOOL success = [xmlParser parse];
	
	if(success)
	{
		NSLog(@"No Errors");
		if ([m_pArrFriends count] ==0) {
			_blockerView.alpha =0.0;
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"its not found" message:@"Please try with others!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[alert show];
			
			[alert release];
		}else {
			_blockerView.alpha =0.0;
			[g_AppDelegate openFeaturedMembersWithMembers:m_pArrFriends];
		}

	}
	else
	{
		NSLog(@"Error Error Error!!!");
	}
	[connection release];
	[m_pWebData release];
}


#pragma mark -
#pragma mark delegate xmlParser
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
	attributes:(NSDictionary *)attributeDict {
	if(!currentElement) 
		currentElement = [[NSString alloc] initWithString:elementName];
	else
		currentElement = [elementName retain];
	
	NSLog(@"Processing Element: %@", elementName);
	
	//iCurrCount = iCountFriend;
	if([currentElement isEqualToString:kUserID]){
		iCountFriend++;
		if(iCountFriend >=2){
			[m_pArrFriends addObject:m_pDictUserInfo];
		}
		[m_pDictUserInfo release];
		m_pDictUserInfo = nil;
		m_pDictUserInfo = [[NSMutableDictionary alloc] init];
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
	NSLog(@"Processing Value: %@", string);
	
	if([currentElement isEqualToString:kUserID]){
		[m_pDictUserInfo setObject:string forKey:kUserID];
	}
	if([currentElement isEqualToString:kUserName]){
		[m_pDictUserInfo setObject:string forKey:kUserName];
	}
	if([currentElement isEqualToString:kFirstName]){
		[m_pDictUserInfo setObject:string forKey:kFirstName];
	}
	if([currentElement isEqualToString:kLastName]){
		[m_pDictUserInfo setObject:string forKey:kLastName];
	}
	if([currentElement isEqualToString:kEmail]){
		[m_pDictUserInfo setObject:string forKey:kEmail];
	}
	if([currentElement isEqualToString:kAvatar]){
		[m_pDictUserInfo setObject:string forKey:kAvatar];
	}
	if([currentElement isEqualToString:kUserType]){
		[m_pDictUserInfo setObject:string forKey:kUserType];
	}
	if([currentElement isEqualToString:kFacebookID]){
		[m_pDictUserInfo setObject:string forKey:kFacebookID];
	}
	if([currentElement isEqualToString:kTwitterID]){
		[m_pDictUserInfo setObject:string forKey:kTwitterID];
	}
	if([currentElement isEqualToString:kFollow]){
		[m_pDictUserInfo setObject:string forKey:kFollow];
	}
	
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName 
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
	
	[currentElement release];
	currentElement = nil;
	[currentElementValue release];
	currentElementValue = nil;
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
